import { useState } from 'react';
import type { StepProps } from './types';
import type { ImportItem } from './types';
import { 
  RiskLevel, 
  ComplianceStatus,
  getRiskLevelOptions,
  getComplianceStatusOptions
} from '@/types/work';
import { exportComplianceItemsToExcel, getAssessmentTypeName } from '@/utils/utils';
import { showMessage } from '@/components/common/MessageTip';
import * as XLSX from 'xlsx-js-style';
import { useBusiness } from '@/stores/useBusinessStore';

/**
 * 根据评估类型生成风险等级反向映射（文本 -> 枚举值）
 * @param assessmentType 评估类型
 * @returns 文本到枚举值的映射对象
 */
const getRiskLevelReverseMap = (assessmentType?: string): Record<string, RiskLevel> => {
  const options = getRiskLevelOptions(assessmentType);
  return options.reduce((acc, item) => {
    acc[item.label] = item.value;
    return acc;
  }, {} as Record<string, RiskLevel>);
};

/**
 * 根据评估类型生成合规状态反向映射（文本 -> 枚举值）
 * @param assessmentType 评估类型
 * @returns 文本到枚举值的映射对象
 */
const getComplianceStatusReverseMap = (assessmentType?: string): Record<string, ComplianceStatus> => {
  const options = getComplianceStatusOptions(assessmentType);
  return options.reduce((acc, item) => {
    acc[item.label] = item.value;
    return acc;
  }, {} as Record<string, ComplianceStatus>);
};

const DownloadStep = ({ onNext, onClose, items }: StepProps) => {
  const [file, setFile] = useState<File | null>(null);
  const [hasDownloaded, setHasDownloaded] = useState(false);
  const { selectedBusiness } = useBusiness();

  const handleDownloadTemplate = async () => {
    if (!items || items.length === 0) {
      showMessage('warning', '请刷新页面重试！');
      return;
    }

    try {
      await exportComplianceItemsToExcel(
        items,
        `${selectedBusiness?.name}_${getAssessmentTypeName(selectedBusiness?.assessmentType || '101')}_导入模板.xlsx`,
        selectedBusiness?.assessmentType || '101', // 使用当前评估类型
        true // 新增参数，显示ID列
      );
      setHasDownloaded(true);
      showMessage('success', '模板下载成功，请按模板格式填写后再上传');
    } catch (error) {
      showMessage('error', '模板下载失败');
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!hasDownloaded) {
      showMessage('warning', '请先下载模板，按格式填写后再上传');
      e.target.value = ''; // 清空选择的文件
      return;
    }

    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      if (!selectedFile.name.endsWith('.xlsx')) {
        showMessage('error', '请上传 Excel 文件(.xlsx)');
        e.target.value = ''; // 清空选择的文件
        return;
      }
      setFile(selectedFile);
    }
  };

  const handleUpload = async () => {
    if (!hasDownloaded) {
      showMessage('warning', '请先下载模板，按格式填写后再上传');
      return;
    }
    if (!file) return;
    try {
      // 获取当前评估类型的反向映射
      const assessmentType = selectedBusiness?.assessmentType;
      const riskLevelMap = getRiskLevelReverseMap(assessmentType);
      const complianceStatusMap = getComplianceStatusReverseMap(assessmentType);
      
      // 读取Excel文件
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: 'array' });
          
          const importItems: ImportItem[] = [];
          
          // 遍历所有sheet
          workbook.SheetNames.forEach(sheetName => {
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[];
            
            // 跳过空行
            const rows = jsonData.filter(row => row.length > 0);
            if (rows.length === 0) return;
            
            // 查找列索引
            const idColIndex = 0; // ID列（第一列）
            const riskLevelColIndex = rows[0].length - 1; // 风险等级/合规状态列（最后一列）
            const inspectorColIndex = rows[0].length - 2; // 检查员列（倒数第二列）
            
            // 从第一行开始处理
            for (let i = 0; i < rows.length; i++) {
              const row = rows[i];
              const id = row[idColIndex]?.toString();
              const inspector = row[inspectorColIndex]?.toString() || '';
              const statusValue = row[riskLevelColIndex]?.toString() || '';
              
              // 验证ID是否存在且有效
              if (!id) continue;
              
              // 查找对应的原始检查项
              const originalItem = items.find(item => item.id === id);
              if (!originalItem) {
                showMessage('warning', `ID为${id}的检查项不存在，已跳过`);
                continue;
              }

              // 根据检查项类型处理状态值
              let risk_level = originalItem.risk_level;
              let compliance_status = originalItem.compliance_status;

              if (originalItem.compliance_type === 'risk') {
                // 风险评估项：处理风险等级
                const mappedRiskLevel = riskLevelMap[statusValue];
                if (mappedRiskLevel) {
                  risk_level = mappedRiskLevel;
                } else {
                  showMessage('warning', `ID为${id}的检查项风险等级"${statusValue}"无效，使用原值`);
                }
              } else {
                // 合规评估项：处理合规状态
                const mappedStatus = complianceStatusMap[statusValue];
                if (mappedStatus) {
                  compliance_status = mappedStatus;
                } else {
                  showMessage('warning', `ID为${id}的检查项合规状态"${statusValue}"无效，使用原值`);
                }
              }
              
              // 添加到导入列表
              importItems.push({
                id,
                inspector,
                title: originalItem.title,
                description: originalItem.description,
                guide: originalItem.guide,
                compliance_type: originalItem.compliance_type,
                risk_level,
                compliance_status
              });
            }
          });
          
          if (importItems.length === 0) {
            showMessage('error', '未找到有效的导入数据');
            return;
          }
          
          onNext(importItems);
          showMessage('success', `成功解析 ${importItems.length} 条数据`);
        } catch (error) {
          console.error('Excel解析错误:', error);
          showMessage('error', '文件格式错误或数据无效');
        }
      };
      
      reader.onerror = () => {
        showMessage('error', '文件读取失败');
      };
      
      reader.readAsArrayBuffer(file);
    } catch (error) {
      console.error('上传错误:', error);
      showMessage('error', '文件解析失败');
    }
  };

  return (
    <div className="space-y-8">
      {/* 第一步：下载模板 */}
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <div className="flex items-center justify-center w-8 h-8 rounded-full bg-blue-100 text-blue-600 font-medium">
            1
          </div>
          <h3 className="text-xl font-medium">下载并填写导入模板</h3>
        </div>
        
        <p className="text-slate-600 pl-11">
          下载标准模板文件，按照格式要求填写检查项信息。模板包含必填字段说明和示例数据。
        </p>

        <div className="pl-11">
          <button
            onClick={handleDownloadTemplate}
            className="inline-flex items-center px-4 py-2 bg-black text-white rounded-md hover:bg-black/90 transition-colors"
          >
            <svg 
              className="w-5 h-5 mr-2" 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path 
                strokeLinecap="round" 
                strokeLinejoin="round" 
                strokeWidth={2} 
                d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
              />
            </svg>
            下载模板
          </button>

          <div className="mt-4 bg-blue-50 border border-blue-100 rounded-lg p-4 space-y-2">
            <div className="flex items-center gap-2 text-blue-600">
              <svg 
                className="w-5 h-5" 
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path 
                  strokeLinecap="round" 
                  strokeLinejoin="round" 
                  strokeWidth={2} 
                  d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
              <span className="font-medium">模板说明：</span>
            </div>
            <ul className="space-y-1 text-sm text-slate-600 pl-7">
              <li>• 模版不包含标题列，请勿添加标题列</li>
              <li>• 必填字段不能为空</li>
              <li>• 请先下载并使用最新模板，避免格式不匹配</li>
            </ul>
          </div>
          {!hasDownloaded && (
            <div className="mt-2 text-sm text-amber-600 flex items-center gap-1">
              <svg 
                className="w-4 h-4" 
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path 
                  strokeLinecap="round" 
                  strokeLinejoin="round" 
                  strokeWidth={2} 
                  d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                />
              </svg>
              <span>请先下载最新模板</span>
            </div>
          )}
        </div>
      </div>

      {/* 第二步：上传文件 */}
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <div className="flex items-center justify-center w-8 h-8 rounded-full bg-slate-100 text-slate-600 font-medium">
            2
          </div>
          <h3 className="text-xl font-medium">上传填写好的文件</h3>
        </div>
        
        <p className="text-slate-600 pl-11">
          选择已填写完成的模板文件进行上传。系统将自动验证数据格式和完整性。
        </p>

        <div className="pl-11">
          <div className="flex items-center justify-center w-full">
            <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-slate-300 border-dashed rounded-lg cursor-pointer bg-slate-50 hover:bg-slate-100">
              <div className="flex flex-col items-center justify-center pt-5 pb-6">
                <svg 
                  className="w-8 h-8 mb-3 text-slate-400" 
                  fill="none" 
                  stroke="currentColor" 
                  viewBox="0 0 24 24"
                >
                  <path 
                    strokeLinecap="round" 
                    strokeLinejoin="round" 
                    strokeWidth={2} 
                    d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                  />
                </svg>
                <p className="mb-2 text-sm text-slate-500">
                  <span className="font-medium">点击上传文件</span> 或拖放文件到此处
                </p>
                <p className="text-xs text-slate-500">仅支持 .xlsx 格式文件</p>
              </div>
              <input
                type="file"
                accept=".xlsx"
                onChange={handleFileChange}
                className="hidden"
              />
            </label>
          </div>
          {file && (
            <div className="mt-2 text-sm text-slate-600">
              已选择文件：{file.name}
            </div>
          )}
        </div>
      </div>

      {/* 底部按钮 */}
      <div className="flex justify-end space-x-3 pt-4">
        <button
          onClick={onClose}
          className="px-4 py-2 border border-slate-200 text-slate-700 rounded-md hover:bg-slate-50"
        >
          取消
        </button>
        <button
          onClick={handleUpload}
          disabled={!file}
          className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          下一步
        </button>
      </div>
    </div>
  );
};

export default DownloadStep;
